package com.ruoyi.project.configureSystem.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.project.configureSystem.domain.StationPicture;
import com.ruoyi.project.configureSystem.domain.SysArea;
import com.ruoyi.project.configureSystem.domain.SysAreaStation;
import com.ruoyi.project.configureSystem.service.ISysAreaService;
import com.ruoyi.project.tool.morqingren.domain.SuECard;
import com.ruoyi.project.tool.morqingren.service.SuECardService;
import com.ruoyi.project.tool.morqingren.util.RandomNumber;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.configureSystem.domain.VStation;
import com.ruoyi.project.configureSystem.service.IVStationService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 厂站信息Controller
 * 
 * @author wangshuo
 * @date 2020-05-13
 */
@RestController
@RequestMapping("/configureSystem/vstation")
public class VStationController extends BaseController
{
    @Autowired
    private IVStationService vStationService;
    @Autowired
    private  SuECardService suECardService;
    @Autowired
    private ISysAreaService areaService;

    /**
     * 查询厂站信息列表
     */
    @PreAuthorize("@ss.hasPermi('configureSystem:vstation:list')")
    @GetMapping("/list")
    public TableDataInfo list(VStation vStation)
    {
        startPage();
        List<VStation> list = vStationService.selectVStationList(vStation);
        return getDataTable(list);
    }

    /**
     * 导出厂站信息列表
     */
    @PreAuthorize("@ss.hasPermi('configureSystem:vstation:export')")
    @Log(title = "厂站信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(VStation vStation)
    {
        List<VStation> list = vStationService.selectVStationList(vStation);
        ExcelUtil<VStation> util = new ExcelUtil<VStation>(VStation.class);
        return util.exportExcel(list, "vstation");
    }

    /**
     * 获取厂站信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('configureSystem:vstation:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(vStationService.selectVStationById(id));
    }

    /**
     * 新增厂站信息
     */
    @PreAuthorize("@ss.hasPermi('configureSystem:vstation:add')")
    @Log(title = "厂站信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody VStation vStation)
    {
        //新增厂站的时候，首先需要绑定一个组织，把区域id传过来，其次把站点的值传过来
        //传到后台之后，再把数据保存到数据库中
        String number=returnCard();
        if (number!=null){
            vStation.setStationcode("LDKS"+number);
        }
        return toAjax(vStationService.insertVStation(vStation));
    }

    //随机生成6个数字，同时和数据库比对
    private String returnCard() {
            String cardNnumer=RandomNumber.getCard();//调用生成随机数的方法：这里以6位为例
            SuECard suECard = suECardService.selectByCardNum(cardNnumer);//生成的随机数进入数据库中查询一下，看时候有相同的。
            if(suECard != null){//如果有相同的数据
                return returnCard();//再次调用方法，生成一个随机数
            }else{//否则
                //把随机生成的六位数保存到数据库表格里面 suc_card
                SuECard scard=new SuECard();
                scard.setRunNumber(cardNnumer);
                suECardService.insertSuECard(scard);
                return cardNnumer;//这个数据我就要

            }
    }

    /**
     * 修改厂站信息
     */
    @PreAuthorize("@ss.hasPermi('configureSystem:vstation:edit')")
    @Log(title = "厂站信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody VStation vStation)
    {
        return toAjax(vStationService.updateVStation(vStation));
    }

    /**
     * 删除厂站信息
     */
    @PreAuthorize("@ss.hasPermi('configureSystem:vstation:remove')")
    @Log(title = "厂站信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(vStationService.deleteVStationByIds(ids));
    }

    /**
     * 获取区域下拉树列表(带站点)
     */
    @GetMapping("/treeStationselect")
    public AjaxResult treeStationselect(SysArea area)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        area.setUserId(loginUser.getUser().getUserId());
        List<SysAreaStation> areas = areaService.selectAreaAndStationList(area);
        return AjaxResult.success(areaService.buildAreaStationTreeSelect(areas));
    }

    /**
     * 获取角色管理的站点列表
     */
    @GetMapping("/getStationByRole")
    public AjaxResult getStationByRole(VStation vStation)
    {
        return AjaxResult.success(vStationService.getStationByRole(vStation));
    }

    /**
     * 获取角色管理的站点列表
     */
    @Autowired
    private ServerConfig serverConfig;
    @PostMapping("/uploadImg")
    public AjaxResult uploadImg(@RequestParam("file") MultipartFile[] file) throws Exception
    {
        try
        {
            List<String> urls = new ArrayList<>();
            // 上传文件路径
            String filePath = RuoYiConfig.getStationPicPath();
            System.out.println("kkk"+filePath);
            Arrays.stream(file).forEach(x->{
                String fileName = null;
                try {
                    fileName = FileUploadUtils.stationPicUpload(filePath, x);
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new BaseException("上传图片失败");
                }
                String url = serverConfig.getUrl() + fileName;
                System.out.println("1=+++"+fileName);
                urls.add(url);

            });
            // 上传并返回新文件名称
            AjaxResult ajax = AjaxResult.success();
//            ajax.put("fileName", fileName);
//            ajax.put("url", url);
            ajax.put("urls",urls);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/delImg")
    public AjaxResult uploadImg(@RequestBody StationPicture stationPicture)
    {
        int i = vStationService.delStationImg(stationPicture.getUrl(),stationPicture.getStationId());
        return AjaxResult.success(i);
    }
}
